package com.hanbang.mrcm.merchant;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hanbang.mrcm.R;
import com.hanbang.mrcm.adapter.BannerAdAdapter;
import com.hanbang.mrcm.base.BaseActivity;
import com.hanbang.mrcm.bean.BannerAdData;
import com.hanbang.mrcm.bean.ScantronData;
import com.hanbang.mrcm.myview.MyDialog;
import com.hanbang.mrcm.myview.MyDialog.MODE;
import com.hanbang.mrcm.utils.HttpInterfaces;
import com.hanbang.mrcm.utils.JsonHelper;
import com.hanbang.mrcm.utils.MyRequestCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class ScantronActivity extends BaseActivity {

	private ScantronData scantronData = null;
	private LinearLayout scrollViewLl = null;
	private int activityId = -1;
	private int type = -1;
	private PullToRefreshScrollView scrollView = null;
	private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<BannerAdData>();
	private BannerAdAdapter bannerAdAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activityId = getIntent().getIntExtra("activity_id", activityId);
		type = getIntent().getIntExtra("type", type);
		setContentView(R.layout.scantron);
		initView();
		setOnClickListener();
		getServiceData();
		getTopData();
	}

	/*
	 * 设置点击事件
	 */
	private void setOnClickListener() {

	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.option_tag_button:
				commitAnswer(v.getTag().toString());
				break;

			default:
				break;
			}
		}
	};

	/*
	 * 初始化view
	 */
	private void initView() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.top_bar_left_image));
		setTitle(findViewById(R.id.top_bar_title), "答题");
		scrollViewLl = (LinearLayout) findViewById(R.id.scrollview_ll);

		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);
		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				bannerAdDatas.clear();
				getTopData();

			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {

			}
		});

		bannerAdAdapter = new BannerAdAdapter(this,
				(RelativeLayout) findViewById(R.id.banner_ad), bannerAdDatas);
		bannerAdAdapter.setWidthAndHeight(16, 9);
		bannerAdAdapter.notifyDataSetChanged();

	}

	private void getServiceData() {
		if (!isLogin(true)) {
			finish();
			return;
		}
		httpUtils.send(HttpMethod.GET, HttpInterfaces.getanswert + "&mobile="
				+ userData.getMobile() + "&password=" + userData.getPassword()
				+ "&activity_id=" + activityId + "&type=" + type,
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								scantronData = JsonHelper.parseObject(json
										.getJSONArray("result")
										.getJSONObject(0), ScantronData.class);
								setTitle(findViewById(R.id.top_bar_title),
										scantronData.getUser_name());
								if (scantronData != null) {
									// 问题
									((TextView) findViewById(R.id.wenti))
											.setText("问题: "
													+ scantronData.getTitle());
									if (scantronData.getOption_a() != null
											&& !"".equals(scantronData
													.getOption_a().trim())) {
										// 选项a
										addOption("A",
												scantronData.getOption_a());
									}
									if (scantronData.getOption_b() != null
											&& !"".equals(scantronData
													.getOption_b().trim())) {
										// 选项b
										addOption("B",
												scantronData.getOption_b());
									}
									if (scantronData.getOption_c() != null
											&& !"".equals(scantronData
													.getOption_c().trim())) {
										// 选项c
										addOption("C",
												scantronData.getOption_c());
									}
									if (scantronData.getOption_d() != null
											&& !"".equals(scantronData
													.getOption_d().trim())) {
										// 选项d
										addOption("D",
												scantronData.getOption_d());
									}
								}
							}

						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});
	}

	/*
	 * 把答案提交 生成兑换码 &answer_id=10&answer=B
	 */
	private void commitAnswer(String res) {
		if (!isLogin(true)) {
			return;
		}
		httpUtils.send(HttpMethod.GET, HttpInterfaces.getCdker + "&mobile="
				+ userData.getMobile() + "&password=" + userData.getPassword()
				+ "&activity_id=" + activityId + "&type=" + type
				+ "&answer_id=" + scantronData.getId() + "&answer=" + res,
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								showToast(1, "回答正确!", "您获得一个红包");
							} else if (status == 0) {
								showToast(0, "回答错误!", "谢谢参与");
							} else if (status == -100) {
								passwordIsError(false);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				});

	}

	protected void showToast(final int r, String res, String content) {

		dialog = new MyDialog(this, R.style.base_dialog, MODE.ANSWER_OK);
		dialog.setTitle(res);
		dialog.setContent(content);
		dialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (r == 0) {
					ScantronActivity.this.finish();
				} else if (r == 1) {
					final MyDialog dialog2 = new MyDialog(
							ScantronActivity.this, R.style.base_dialog,
							MODE.ANSWER_OK);
					dialog2.setContentView(R.layout.hongbao);
					dialog2.getWindow().getAttributes().gravity = Gravity.CENTER;
					dialog2.setCancelable(false);
					dialog2.findViewById(R.id.imageview).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									Intent intent = new Intent();
									intent.setClass(ScantronActivity.this,
											HongBaoOpenActivity.class);
									intent.putExtra("type", type);
									intent.putExtra("activity_id", activityId);
									startActivity(intent);
									dialog2.dismiss();
									finish();
								}
							});
					dialog2.show();
				}
			}
		});

		dialog.show();
		timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				mainHandler.sendEmptyMessage(100);
			}
		}, 2000);
	}

	MyDialog dialog = null;
	private Timer timer = null;
	@SuppressLint("HandlerLeak")
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 100) {
				timer.cancel();
				timer = null;
				dialog.dismiss();
				dialog = null;
			}
		}
	};

	@SuppressLint("InflateParams")
	private void addOption(String optionTag, String option) {
		View view = LayoutInflater.from(this).inflate(R.layout.scantron_item,
				null);
		((TextView) view.findViewById(R.id.option_tag)).setText(optionTag
				+ ": ");
		((TextView) view.findViewById(R.id.option)).setText(option);
		TextView button = (TextView) view.findViewById(R.id.option_tag_button);
		button.setTag(optionTag);
		button.setText(optionTag);
		button.setOnClickListener(onClickListener);
		scrollViewLl.addView(view);
	}

	private void getTopData() {
		httpUtils.send(HttpMethod.GET, HttpInterfaces.goodPic + "&activity_id="
				+ activityId, new MyRequestCallBack<String>(this,
				getString(R.string.loadding)) {
			@Override
			public void onFailure(HttpException error, String msg) {
				super.onFailure(error, msg);
				scrollView.onRefreshComplete();
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				super.onSuccess(responseInfo);
				try {
					JSONObject json = new JSONObject(responseInfo.result);
					int status = json.getInt("status");
					if (status == 1) {
						JSONArray result = json.getJSONArray("result");
						for (int i = 0; i < result.length(); i++) {
							BannerAdData data = new BannerAdData();
							JSONObject item = result.getJSONObject(i);
							data.setActivity_id(item.getInt("article_id"));
							data.setImg_url(item.getString("original_path"));
							bannerAdDatas.add(data);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				scrollView.onRefreshComplete();
				bannerAdAdapter.notifyDataSetChanged();

			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
